angular.module('panels')
    .directive('panelItilServiceDeskTodoEventList', function ($http, $timeout, loadConf, LoginInfo, tabService, $log, Promise) {
        return {
            scope: {},
            link: function (scope, elem) {
                var iconColors = ["#7cb5ec", "#90ed7d", "#f7a35c", "#8085e9", "#f15c80", "#e4d354", "#8d4653", "#91e8e1", "#6b8e23", "#ee82ee", "#800080"];
                scope.getIconColor = function (alarm) {
                    var code = 0, typeName = alarm.eventPerson || '';
                    for (var i = 0; i < typeName.length; i++) {
                        code += typeName.charCodeAt(i);
                    }
                    return iconColors[code % 100 % iconColors.length];
                };
                scope.events = [];
                Promise.all({
                    setting: loadConf('panel-itil-service-desk-todo-event-list.yml'),
                    loginInfo: LoginInfo
                }).then(function (result) {// 更新noticeList
                    var setting = result.setting, loginInfo = result.loginInfo, timeoutId;
                    scope.more = setting.more;
                    scope.$on('$destroy', function () {
                        timeoutId && $timeout.cancel(timeoutId);
                    });
                    (function updateData() {
                        $http.jsonp(setting.listQueryUrl.replace('{userId}', loginInfo.currentUser.LOGIN_ID)).success(function (list) {
                            scope.events = list;
                        }).then(callback, callback);
                        function callback() {
                            if (setting.updateInterval > 0) {
                                timeoutId = $timeout(updateData, setting.updateInterval * 1000);
                            }
                        }

                        $log.debug('panel update data: itil-service-desk-todo-event-list')
                    }());
                    scope.openDetail = function (event) {
                        if (setting.viewDetailUrl) {
                            var viewDetailUrl = setting.viewDetailUrl.replace(/\{eventId}/g, event.eventId || '');
                            tabService.addTab({name: '服务台告警:' + event.eventContent, url: viewDetailUrl});
                        }
                    };
                });
            },
            templateUrl: 'app/panel/itil/service-desk-todo-event-list.html'
        };
    });